<?php defined('BASEPATH') OR exit('No direct script access allowed');

// Code here is run before admin controllers
class Admin_Controller extends MY_Controller
{
    public $arr = array();

    public function __construct()
    {
        parent::__construct();

        // Load the Language files ready for output
        $this->lang->load('admin');
        $this->load->helper('admin_theme');

        // Show error and exit if the user does not have sufficient permissions
        if (!self::_check_access()) {
            show_error($this->lang->line('cp_access_denied'));
            exit;
        }

        if (!$this->admin_theme->slug) {
            show_error('This site has been set to use an admin theme that does not exist.');
        }

        // Prepare Asset library
        $this->asset->set_theme(ADMIN_THEME);

        // grab the theme options if there are any
        $this->theme_options = $this->pyrocache->model('themes_m', 'get_values_by', array(array('theme' => ADMIN_THEME)));

        // Template configuration
        $this->template
                ->enable_parser(FALSE)
                ->set('user', $this->user)
                ->set('theme_options', $this->theme_options)
                ->set_theme(ADMIN_THEME)
                ->set_layout('default', 'admin');

        // trigger the run() method in the selected admin theme
        $class = 'Theme_' . ucfirst($this->admin_theme->slug);
        call_user_func(array(new $class, 'run'));

        //	    $this->output->enable_profiler(TRUE);
    }

    private function _check_access()
    {
        // These pages get past permission checks
        $ignored_pages = array('admin/login', 'admin/logout');

        // Check if the current page is to be ignored
        $current_page = $this->uri->segment(1, '') . '/' . $this->uri->segment(2, 'index');

        // Dont need to log in, this is an open page
        if (in_array($current_page, $ignored_pages)) {
            return TRUE;
        }
        else if (!$this->user) {
            redirect('admin/login');
        }

            // Admins can go straight in
        else if ($this->user->group === 'admin') {
            return TRUE;
        }

            // Well they at least better have permissions!
        else if ($this->user) {
            // We are looking at the index page. Show it if they have ANY admin access at all
            if ($current_page == 'admin/index' && $this->permissions) {
                return TRUE;
            }
            else
            {
                // Check if the current user can view that page
                return array_key_exists($this->module, $this->permissions);
            }
        }

        // god knows what this is... erm...
        return FALSE;
    }
    /**
     * Form Control
     *
     * Returns the form control for the theme option
     *
     * @param    object    $option
     * @return    string
     */
    public function form_control(&$option)
    {
        if ($option->options) {
            if (substr($option->options, 0, 5) == 'func:') {
                if (is_callable($func = substr($option->options, 5))) {
                    $option->options = call_user_func($func);
                }
                else
                {
                    $option->options = array('=' . lang('select.none'));
                }
            }

            if (is_string($option->options)) {
                $option->options = explode('|', $option->options);
            }
        }

        switch ($option->type)
        {
            default:
            case 'text':
                $form_control = form_input(array(
                                                'id' => $option->slug,
                                                'name' => $option->slug,
                                                'value' => $option->value,
                                                'class' => 'text width-20'
                                           ));
                break;

            case 'textarea':
                $form_control = form_textarea(array(
                                                   'id' => $option->slug,
                                                   'name' => $option->slug,
                                                   'value' => $option->value,
                                                   'class' => 'width-20'
                                              ));
                break;

            case 'password':
                $form_control = form_password(array(
                                                   'id' => $option->slug,
                                                   'name' => $option->slug,
                                                   'value' => $option->value,
                                                   'class' => 'text width-20',
                                                   'autocomplete' => 'off',
                                              ));
                break;

            case 'select':
                $form_control = form_dropdown($option->slug, $this->_format_options($option->options), $option->value, 'class="width-20"');
                break;

            case 'select-multiple':
                $options = $this->_format_options($option->options);
                $size = sizeof($options) > 10 ? ' size="10"' : '';
                $form_control = form_multiselect($option->slug . '[]', $options, explode(',', $option->value), 'class="width-20"' . $size);
                break;

            case 'checkbox':

                $form_control = '';
                $stored_values = is_string($option->value) ? explode(',', $option->value) : $option->value;

                foreach ($this->_format_options($option->options) as $value => $label)
                {
                    if (is_array($stored_values)) {
                        $checked = in_array($value, $stored_values);
                    }
                    else
                    {
                        $checked = FALSE;
                    }

                    $form_control .= '<label>';
                    $form_control .= '' . form_checkbox(array(
                                                             'id' => $option->slug . '_' . $value,
                                                             'name' => $option->slug . '[]',
                                                             'checked' => $checked,
                                                             'value' => $value
                                                        ));
                    $form_control .= ' ' . $label . '</label>';
                }
                break;

            case 'radio':

                $form_control = '';
                foreach ($this->_format_options($option->options) as $value => $label)
                {
                    $form_control .= '' . form_radio(array(
                                                          'id' => $option->slug,
                                                          'name' => $option->slug,
                                                          'checked' => $option->value == $value,
                                                          'value' => $value
                                                     )) . ' ' . $label . '';
                }
                break;
            case 'upload':
                $form_control = '';
                $form_control .= '' . form_upload(array(
                                                       'id' => $option->slug,
                                                       'name' => $option->slug,
                                                       'class' => 'input'
                                                  ));
                $form_control .= '<div class="clear-both text-small1" style="margin-left: 160px;"><img src="' . BASE_URL . 'uploads/files/' . $option->value . '"/></div>';
                break;
        }

        return $form_control;
    }

    /**
     * Format Options
     *
     * Formats the options for a theme option into an associative array.
     *
     * @param    array    $options
     * @return    array
     */
    private function _format_options($options = array())
    {
        $select_array = array();

        foreach ($options as $option)
        {
            list($value, $name) = explode('=', $option);

            $select_array[$value] = $name;
        }

        return $select_array;
    }

}